package com.zpark.blog.servlet;


// 处理用户登录请求
import com.zpark.blog.dao.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // 假设这是你的用户数据访问对象
    private UserDAO userDao = new UserDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");

        // 获取用户名和密码参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 验证用户名和密码
        if (userDao.validate(username, password)) {
            // 登录成功：设置会话属性并重定向到主页
            request.getSession().setAttribute("user", username);
            response.sendRedirect("blog_list.html");
        } else {
            // 登录失败：返回登录页面并显示错误信息
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("/login.html").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 处理GET请求，通常只是展示登录页面
        request.getRequestDispatcher("/login.html").forward(request, response);
    }
}